package system.task.logger;

import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.springframework.util.StringUtils;
import system.task.config.TaskConfig;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class TaskLoggerFileWriter implements TaskLoggerWriter {
    private final TaskConfig taskConfig;
    private BufferedWriter writer = null;
    @Getter
    private final String path;
    @Getter
    private final boolean enable;
    @Getter
    @Setter
    private boolean hasContent = false;

    public TaskLoggerFileWriter(TaskConfig taskConfig, String path) {
        this.taskConfig = taskConfig;
        this.path = path;
        this.enable = StringUtils.hasText(path);
    }

    @SneakyThrows
    protected synchronized void writeContent(String s) {
        if (writer == null) {
            File f = new File(this.path);
            File parent = f.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            writer = new BufferedWriter(new FileWriter(f), taskConfig.getWriterBuffer());
            hasContent = true;
        }
        writer.write(s);
    }

    @Override
    public synchronized void close() throws Exception {
        BufferedWriter w = this.writer;
        if (w != null) {
            this.writer = null;
            w.flush();
            w.close();
        }
    }

    @Override
    public void info(String time, String message, boolean newLine) {
        if (this.enable) {
            writeContent(TaskLoggerUtil.buildContent(time, message, newLine).toString());
        }
    }

    @Override
    public void error(String time, String message, boolean newLine) {
        if (this.enable) {
            writeContent(TaskLoggerUtil.buildError(time, message, newLine).toString());
        }
    }
}
